#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,ans,a[1010];
const int mod=998244353;
struct tree{
	vector<int> edge[1010];
	int rt,fa[1010],dep[1010],siz[1010],son[1010],top[1010];
	void dfs1(int u){
		siz[u]=1;
		for(auto &i:edge[u]){
			dep[i]=dep[u]+1;
			dfs1(i);
			siz[u]+=siz[i];
			if(siz[i]>siz[son[u]]) son[u]=i;
		}
	}
	void dfs2(int u,int t){
		top[u]=t;
		if(son[u]) dfs2(son[u],t);
		for(auto &i:edge[u])
			if(i!=son[u]) dfs2(i,i);
	}
	int lca(int u,int v){
		while(top[u]!=top[v]){
			if(dep[top[u]]<dep[top[v]]) swap(u,v);
			u=fa[top[u]];
		}
		if(dep[u]<dep[v]) return u;
		else return v;
	}
	int find(int u,int v){
		while(top[u]!=top[v]){
			if(fa[top[v]]==u) return siz[top[v]];
			v=fa[top[v]];
		}
		return siz[son[u]];
	}
}t1,t2;
signed main(){
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout);
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%lld",&t1.fa[i]);
		if(t1.fa[i]==0) t1.rt=i;
		t1.edge[t1.fa[i]].push_back(i);
	}
	for(int i=1;i<=m;i++){
		scanf("%lld",&t2.fa[i]);
		if(t2.fa[i]==0) t2.rt=i;
		t2.edge[t2.fa[i]].push_back(i);
	}
	for(int i=1;i<=n;i++)
		scanf("%lld",&a[i]);
	t1.dep[t1.rt]=1,t2.dep[t2.rt]=1;
	t1.dfs1(t1.rt),t1.dfs2(t1.rt,t1.rt);
	t2.dfs1(t2.rt),t2.dfs2(t2.rt,t2.rt);
	for(int i=1;i<=n;i++)
		for(int j=i+1;j<=n;j++){
			int num=t2.dep[t2.lca(a[i],a[j])];
			int l=t1.lca(i,j);
			int u=i,v=j;
			if(t1.dep[u]>t1.dep[v]) swap(u,v);
			if(u==l) num*=t1.siz[v]*(n-t1.find(u,v))%mod,num%=mod;
			else num*=t1.siz[u]*t1.siz[v]%mod,num%=mod;
			ans+=num,ans%=mod;
		}
	printf("%lld",ans);
	return 0;
}
